<template>
  <!-- 数据监测 -->
  <treeBox v-loading="totalLoading">
    <template #tree>
      <TreeList :tree-data="treeData" />
    </template>
    <template #detailBody>
      <div class="tree-right-detail-box">
        <CardSearch ref="cardSearch" :config="cardSearchConfig" />
        <CardTable ref="cardTable" :config="cardTableConfig" />
      </div>
    </template>
  </treeBox>
</template>

<script>
import CardSearch from '@/components/cardSearch/index.vue'
import CardTable from '@/components/cardTable/index.vue'
import { tBaseMixin } from '@/views/layout/treeOrDetailFrame/components/tBaseMixIn'
import { getProjectRoot } from '@/api/project'
import { removeSlash } from '@/utils/removeIdSlash'
import TreeList from '@/components/treeList/index.vue'
import { getDeviceVarGroup, getDevice, getDatasList } from '@/api/device'
import { TrueExcel } from '@/utils/exportExcel' // , Download
import useGlobal from '@/hooks/global/useGlobal'
const { $message, $format, $btnPerms } = useGlobal()

export default {
  components: { CardTable, CardSearch, TreeList },
  mixins: [tBaseMixin],
  data() {
    return {
      totalLoading: false,
      excel: new TrueExcel(),
      cardSearchConfig: {
        operation: {
          search: { text: '查询', handle: () => this.refreshData() },
          export: {
            text: '导出',
            perm: $btnPerms('data_export'),
            perm: true,
            handleDisabled: () => !this.cardTableConfig.selectList.length,
            handle: () => this.exportData()
          }
        },
        defaultParams: {
          group: ''
        },
        filters: [
          {
            label: '采集器',
            key: 'sensorId',
            type: 'select',
            width: '240px',
            options: [],
            handleChange: val => this.getDeviceVarGroup(val)
          },
          {
            label: '设备',
            key: 'group',
            type: 'select',
            width: '240px',
            options: [{ label: '全部', value: '' }]
          }
        ]
      },
      cardTableConfig: {
        loading: false,
        dataList: [],
        indexVisible: {
          label: '序号',
          width: '50px',
          align: 'center'
        },
        columns: [
          { prop: 'serialNumber', label: '测量设备点位' },
          { prop: 'serialNumber', label: '探头ID' },
          {
            prop: 'collectionTime',
            label: '最后更新时间',
            formatter: row => $format(row.collectionTime),
            icon: 'el-icon-time',
            iconStyle: {
              color: '#69e850',
              display: 'inline-block',
              'font-size': '16px'
            }
          },
          { prop: 'propertyName', label: '监测量' },
          {
            prop: 'value',
            label: '监测值',
            formatter: row => (row.value || '-') + row.unit,
            cellStyle: {
              color: 'darkblue',
              'font-weight': 600,
              'font-size': '20px'
            }
          }
        ],
        pagination: {
          page: 1,
          limit: 20,
          total: 0,
          layout: 'total, sizes, prev, pager, next, jumper',
          sizeHandle: val => {
            this.cardTableConfig.pagination.limit = val
            this.refreshData()
          },
          pageHandle: val => {
            this.cardTableConfig.pagination.page = val
            this.refreshData()
          }
        }
      },
      treeData: {
        that: this,
        title: '项目列表',
        data: [],
        loading: false,
        isFilterTree: true,
        currentId: '',
        currentProject: {},
        expandNodeId: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        treeNodeHandleClick: data => {
          // 设置当前选中项目信息
          this.treeData.currentProject = data
          this.getProjectData()
        }
      }
    }
  },
  created() {
    this.refreshTree(true)
    this.refreshInterval = setInterval(() => this.refreshData(), 30 * 1000)
  },

  methods: {
    // 点击项目 获取项目下的主机从机
    getProjectData() {
      getDevice(this.treeData.currentProject.id).then(res => {
        this.cardSearchConfig.filters[0].options = res.data.map(item => ({
          label: item.name,
          value: removeSlash(item.id.id)
        }))
        if (res.data[0]) {
          if (this.$refs && this.$refs.cardSearch) {
            this.$refs.cardSearch.queryParams.sensorId = removeSlash(res.data[0].id.id)
          } else {
            this.cardSearchConfig.defaultParams = {
              group: '',
              sensorId: removeSlash(res.data[0].id.id)
            }
          }
          this.getDeviceVarGroup(removeSlash(res.data[0].id.id))
        }
      })
    },

    getDeviceVarGroup(sensorId) {
      getDeviceVarGroup(sensorId).then(res => {
        console.log(res.data)
        this.refreshData()
      })
    },

    async refreshData() {
      this.cardTableConfig.loading = true
      const paramsObj = {
        page: this.cardTableConfig.pagination.page,
        size: this.cardTableConfig.pagination.limit,
        projectId: this.treeData.currentProject.id
      }
      if (this.$refs && this.$refs.cardSearch) {
        Object.assign(paramsObj, this.$refs.cardSearch.queryParams)
      } else {
        Object.assign(paramsObj, this.cardSearchConfig.defaultParams)
      }

      if (!paramsObj.sensorId) return (this.cardTableConfig.loading = false)

      const res = await getDatasList(paramsObj.sensorId, {
        group: paramsObj.group,
        page: paramsObj.page,
        size: paramsObj.size
      })
      console.log(res, 'getDatasListgetDatasList')
      this.cardTableConfig.loading = false

      this.cardTableConfig.dataList = res.data.data
      this.cardTableConfig.pagination.total = res.data.total
    },

    refreshTree() {
      getProjectRoot()
        .then(res => {
          if (res.data) {
            this.treeData.data = res.data
            const fTData = this.treeData.data.filter(v => !v.disabled)
            this.treeData.currentProject = fTData[0]
            this.getProjectData()
            this.totalLoading = false
          } else {
            $message('暂无项目 不可操作，请创建项目')
            this.totalLoading = false
          }
        })
        .catch(err => {
          console.log(err)
          $message('暂无项目 不可操作，请创建项目')
          this.totalLoading = false
        })
    },

    exportData() {
      // export
      this.excel.addElTable(this.$refs.cardTable.$refs.elTable)
      this.excel.export()
    },

    beforeUnmount() {
      clearInterval(this.refreshInterval)
    }
  }
}
</script>

<style lang="scss" scoped>
.cardSearch {
  margin: 16px 0;
  background: #fff;
}
input {
  height: 48px;
}
.tableBox {
  margin-top: 20px;
}
</style>
